import re
from rest_framework import serializers
from .models import CustomUser

from .models import Address
from django.db import transaction
from django.utils.translation import gettext_lazy as _
"""字段参数required的值代表是否必须接收该请求字段，默认为True，即必须接收。
字段参数allow_blank的值代表该字段是否允许为空，默认为False，即不允许为空。
字段参数write_only的值代表该字段是否只用于写入，默认为False，即可以用于写入和读取。
"""
class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True, write_only=True)

class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, min_length=8)
    email = serializers.EmailField(required=False, allow_blank=True)  # 邮箱为可选项

    class Meta:
        model = CustomUser
        fields = ['username', 'password', 'phone', 'email']

    def validate_username(self, value):
        if CustomUser.objects.filter(username=value).exists():
            raise serializers.ValidationError("用户名已存在")
        return value
    
    def validate_phone(self, value):
        if CustomUser.objects.filter(phone=value).exists():
            raise serializers.ValidationError("手机号已注册")
        return value

    def validate_email(self, value):
        if value and CustomUser.objects.filter(email=value).exists():
            raise serializers.ValidationError("邮箱已被注册")
        return value

    def create(self, validated_data):
        # 从 validated_data 中提取邮箱，默认为空字符串
        email = validated_data.pop('email', None)
        user = CustomUser.objects.create_user(**validated_data)
        if email:  # 如果用户填写了邮箱，则保存
            user.email = email
            user.save()
        return user

class ResetPasswordSerializer(serializers.Serializer):
    phone = serializers.CharField(required=False, allow_blank=True)
    email = serializers.EmailField(required=False, allow_blank=True)
    password = serializers.CharField(write_only=True, min_length=8)

    def validate(self, data):
        phone=data.get('phone')
        email=data.get('email')
        if not phone and not email:
            raise serializers.ValidationError('手机号或邮箱必须提供一个')
        return data

class SendCodeSerializer(serializers.Serializer):
    email = serializers.EmailField(required=False, allow_blank=True)
    phone = serializers.CharField(max_length=15, required=False)
    scene = serializers.ChoiceField(
        choices=['register', 'reset_pwd'], 
        required=True,
        help_text="场景类型：register（注册）、reset_pwd（找回密码）"
    )
    def validate(self, data):
        scene = data.get('scene')
        phone = data.get('phone')
        email = data.get('email')

        if scene == 'register':
            if not phone:
                raise serializers.ValidationError({'phone': '注册场景必须提供手机号'})
        elif scene == 'reset_pwd':
            if not (phone or email):
                raise serializers.ValidationError({'phone': '找回密码需要提供手机号或邮箱'})
            if phone and email:
                raise serializers.ValidationError({'phone': '只能选择一种找回方式'})
        
        return data

class VerifyCodeSerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=15, required=False)
    email = serializers.EmailField(required=False,allow_blank=True)
    code = serializers.CharField(max_length=6, required=True)
    scene = serializers.ChoiceField(
        choices=['register', 'reset_pwd'], 
        required=True,
        help_text="场景类型：register（注册）、reset_pwd（找回密码）"
    )

    def validate(self, data):
        scene = data.get('scene')
        phone = data.get('phone')
        email = data.get('email')
        if scene == 'register':
            if not phone:
                raise serializers.ValidationError({'phone': '注册场景必须提供手机号'})
        elif scene == 'reset_pwd':
            if not (phone or email):
                raise serializers.ValidationError({'phone': '找回密码需要提供手机号或邮箱'})
            if phone and email:
                raise serializers.ValidationError({'phone': '只能选择一种找回方式'})
        return data

class ResetPhoneOrEmailSerializer(serializers.Serializer):
    new_email = serializers.EmailField(max_length=50,required=False, allow_blank=True)
    new_phone = serializers.CharField(max_length=15, required=False)
    def validate(self, data):
        new_email = data.get('new_email')
        new_phone = data.get('new_phone')
        if not (new_email or new_phone):
            raise serializers.ValidationError({'error': '至少提供一个新的邮箱或手机号'})
        if new_email and new_phone:
            raise serializers.ValidationError({'error': '一次只能改一个'})
        return data
class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ['username', 'uid', 'avatar_key']
            
class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = [
            'id',
            'receiver_name',
            'receiver_phone',
            'detail',
            'is_default',
            'created_at'
        ]
        extra_kwargs = {
            'is_default': {
                'default': False,  # 关键：设置默认值为 False
                'required': False  # 允许不传该字段
            }
        }
        read_only_fields = ['id', 'created_at', 'user']  # 禁止用户直接修改这些字段

    def validate_is_default(self, value):
        """
        如果设置为默认地址，自动取消其他地址的默认状态
        """
        user = self.context['request'].user
        if value:
            Address.objects.filter(user=user, is_default=True).update(is_default=False)
        return value
#手机号格式验证
    def validate_receiver_phone(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式错误")
        return value
#创建地址时关联用户
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)
